<template>

  <div>
    <table>
      <caption>新增和编辑</caption>
      <tbody>
      <tr>
        <td><label for="">书籍:</label></td>
        <td><input type="text" placeholder="请输入书籍的名称" v-model="formData.bookName"></td>
      </tr>
      <tr>
        <td><label for="">作者:</label></td>
        <td><input type="text" placeholder="请输入书籍的作者" v-model="formData.author"></td>
      </tr>
      <tr>
        <td><label for="">简介:</label></td>
        <td><input type="text" placeholder="请输入书籍的简介" v-model="formData.blurb"></td>
      </tr>
      <tr>
        <td><input type="button" value="保存" @click="btnSave"></td>
        <td><input type="button" value="取消" @click="btnCancel"></td>
      </tr>
      </tbody>
    </table>
  </div>

</template>
<script setup>
import {useRoute, useRouter} from 'vue-router';
import {onMounted, reactive} from "vue";
import {addItem, editItem, getById} from "@/api/bookApi.js";

let formData = reactive({
  bookName: "",
  author: "",
  blurb: ""
})
let router = useRouter();

let route = useRoute()


async function btnSave() {
  let id = route.params.id || 0
  
  let res;

  if (id > 0) {

    res = await editItem(id, formData)


  } else {

    res = await addItem(formData)

  }
  if (res.code = 1000) {

    router.push('/book')

  } else {
    
    console.log(

      res.msg

    )
  }
  console.log(res)
}

function btnCancel() {

  console.log('取消')

  router.push('/book')

}


onMounted(async () =>{
  //从路由中拿到id
  let id = route.params.id || 0;
  console.log(id)

  //当有id时,说明其是编辑，需要发请求，从后端拿数据，并且拿不对劲数据后渲染给表单

  if(id > 0){
    let res = await getById(id);
    formData.bookName=res.data.bookName;
    formData.author =res.data.author;
    formData.blurb=res.data.blurb;
  }
})
</script>
